package com.fuershiye.woman.monitor.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.fuershiye.woman.monitor.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fuershiye.woman.monitor.beans.IdNameSname;
import com.fuershiye.woman.monitor.beans.Page;
import com.fuershiye.woman.monitor.beans.Result;
import com.fuershiye.woman.monitor.beans.ViewReportAllValue;
import com.fuershiye.woman.monitor.constants.Massage;
import com.fuershiye.woman.monitor.model.Department;
import com.fuershiye.woman.monitor.model.FormsDepart;
import com.fuershiye.woman.monitor.utils.DateFormatUtil;
import com.google.common.collect.Maps;

/**
 * 导出管理
 * 
 * @author yongyongdong
 *
 */
@Controller
@RequestMapping(value = "/export")
public class ExportController {

	private static final Logger logger = LoggerFactory
			.getLogger(ExportController.class);

	@Autowired
	ReportService reportService;
	@Autowired
	BridgeService bridgeService;
	@Autowired
	FormsDepartService formsDepartService;
	@Autowired
	DepartmentService departmentService;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/excel/province.do")
	@ResponseBody
	public Result exportdo(Long formsid, String years, HttpServletRequest request) {

		if (StringUtils.isBlank(years)) {
			return new Result(Massage.ERROR_PARAMETER);
		}
		
		List<Integer> yearList = DateFormatUtil.getYearStr2List(years);
		if (yearList.isEmpty()) {
			return new Result(Massage.ERROR_YEAR);
		}

		// 未删除状态数据
		int status = 1;
		
		//部门级别 1:国家级;2:省/部级;3:地级市;4:区县级;5:乡镇级;6:其他
		int level = 2;
		
		List<IdNameSname> departmentList = departmentService.getAllByLevelAndArea(level, null, status);
		List<Long> departIds = departmentService.getDepartIdsFromIdNameSname(departmentList);
		if (departIds.isEmpty()) {
			return new Result(Massage.DEPART_IS_NULL);
		}
		
		List<FormsDepart> formsDepartList = formsDepartService.listByCondtion(departIds, yearList, formsid, status, new Page(1, Integer.MAX_VALUE));
		if(formsDepartList==null||formsDepartList.size()<1){
			return new Result(Massage.REPORT_FORM_DEPART_NULL);
		}

		List<ViewReportAllValue> reportList = reportService.getReportDate(departIds, formsid, null, yearList, 1);
		if (reportList.isEmpty()) {
			return new Result(Massage.REPORT_IS_NULL);
		}

		List<Map<String, Object>> result = reportService.filter(reportList, yearList);
		
		String path= getDonwloadPath(yearList, result, request);
		
		return new Result(Massage.SUCCESS, path);
		
	}
	
	private String getDonwloadPath(List<Integer> yearList, List<Map<String, Object>> reportList, HttpServletRequest request) {
		
		String realPath = request.getSession().getServletContext().getRealPath("/");
		String path = "/export/";
		String domain = request.getServerName();
		int port = request.getServerPort();
		String name = System.currentTimeMillis() + ".xls";
		
		File file = new File(realPath + path);
		if (!file.exists()) {
			if(!file.mkdirs()){
				logger.error("ExportController excel mkdirs is error!");
				return null;
			}
		}
		file = new File(realPath + path + name);
		
		
		
		Department department = bridgeService.getUserDepartment();
		if (department == null) {
			logger.error("ExportController excel department is null!");
			return null;
		}
		
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

		for (Map<String, Object> map : reportList) {
			dataList.add(map);
		}
		
		String[] headers = getHeader(yearList);
		
		dataList.add(new LinkedHashMap<String, Object>());
		dataList.add(new LinkedHashMap<String, Object>());
		
		HashMap<String, Object> mapAuthor = Maps.newHashMap();
		mapAuthor.put("", "单位负责人：" + department.getAuthor());
		dataList.add(mapAuthor);
		
		HashMap<String, Object> mapCharge = Maps.newHashMap();
		mapCharge.put("", "统计负责人：" + department.getAuthor());
		dataList.add(mapCharge);
		
		HashMap<String, Object> mapTel = Maps.newHashMap();
		mapTel.put("", "联系电话：" + department.getPhone());
		dataList.add(mapTel);
		
		
//		logger.info("ExportController file path:" + file.getPath());
//		// 生成本地文件
//		ExportExcel<Report> ex = new ExportExcel<Report>();
//		if (!ex.exportExcel(headers, dataList, file.getPath())) {
//			return null;
//		}
		
		return "http://" + domain + ":" + port + path + name;
	}

	
	private String[] getHeader(List<Integer> yearList){

		String header = "指标名称,汇总代码,计量单位,小数位,资料来源";
		
		for(Integer year: yearList){
			header = header + (year == null ? "" : ","+year); 
		}
		
		return header.split(",");
	}
	
}
